from app import db
from datetime import datetime

class Form(db.Model):
    __tablename__ = 'forms'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=False)
    name = db.Column(db.String(100), nullable=False, comment='表单名称')
    description = db.Column(db.Text, nullable=True, comment='表单描述')
    form_type = db.Column(db.String(50), nullable=False, comment='表单类型')
    structure = db.Column(db.JSON, nullable=False, comment='表单结构(JSON格式)')
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    created_by = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='创建人ID')
    updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    updated_by = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='更新人ID')
    archived_at = db.Column(db.DateTime, nullable=True, comment='归档时间')
    archived_by = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='归档人ID')
    deleted_at = db.Column(db.DateTime, nullable=True, comment='删除时间(软删除)')
    deleted_by = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='删除人ID')
    
    # Define indexes
    __table_args__ = (
        db.Index('idx_user_id', user_id),
        db.Index('idx_form_type', form_type),
        db.Index('idx_created_at', created_at),
        db.Index('idx_deleted_at', deleted_at),
    )
    
    # Define relationships
    user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('forms', lazy=True))
    creator = db.relationship('User', foreign_keys=[created_by], backref='created_forms')
    updater = db.relationship('User', foreign_keys=[updated_by], backref='updated_forms')
    archiver = db.relationship('User', foreign_keys=[archived_by], backref='archived_forms')
    deleter = db.relationship('User', foreign_keys=[deleted_by], backref='deleted_forms')
    
    def __repr__(self):
        return f'<Form {self.name}>'